import json
import os

# Configuration
SOURCE_DIR = r'c:\Users\charl\Desktop\_public_html\data'
OUTPUT_DIR = r'c:\Users\charl\Desktop\_public_html\export_txt'

FILES = {
    'Direito_Administrativo': 'questoes_administrativo.json',
    'Administracao_Geral': 'questoes_administracao.json',
    'Direito_Constitucional': 'questoes_constitucional.json'
}

def format_question(q):
    # Statement
    statement = q.get('statement', '')
    if isinstance(statement, list):
        statement = '\n'.join(statement)
    
    # Options
    options = ""
    opts = q.get('options', {})
    for key, text in opts.items():
        options += f"({key.upper()}) {text}\n"
    
    # Gabarito
    gabarito = q.get('gabarito', '?').upper()
    
    return f"""QUESTÃO {q.get('id', 'N/A')}
{statement}

{options}
GABARITO: {gabarito}
--------------------------------------------------------------------------------
"""

def main():
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)
        print(f"Created directory: {OUTPUT_DIR}")

    for subject, filename in FILES.items():
        json_path = os.path.join(SOURCE_DIR, filename)
        txt_path = os.path.join(OUTPUT_DIR, f"{subject}.txt")
        
        print(f"Processing {subject}...")
        
        try:
            with open(json_path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            with open(txt_path, 'w', encoding='utf-8') as f:
                f.write(f"MATÉRIA: {subject.replace('_', ' ')}\n")
                f.write(f"TOTAL DE QUESTÕES: {len(data)}\n")
                f.write("="*80 + "\n\n")
                
                for q in data:
                    f.write(format_question(q))
                    f.write("\n")
            
            print(f"Saved: {txt_path}")
            
        except Exception as e:
            print(f"Error processing {subject}: {e}")

if __name__ == "__main__":
    main()
